require('dotenv').config();
const { Sequelize } = require('sequelize');

// 创建 Sequelize 实例
const sequelize = new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USER,
    process.env.DB_PASS,
    {
        host: process.env.DB_HOST,
        port: process.env.DB_PORT,
        dialect: 'mysql',
        logging: process.env.NODE_ENV === 'development' ? console.log : false,
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

// 导入模型初始化函数
const initUser = require('./User');
const initCategory = require('./Category');
const initProduct = require('./Product');
const initCart = require('./Cart');
const initOrder = require('./Order');
const initOrderItem = require('./OrderItem');
const initAddress = require('./Address'); // 添加地址模型

// 初始化模型，传递DataTypes
const User = initUser(sequelize, Sequelize.DataTypes);
const Category = initCategory(sequelize, Sequelize.DataTypes);
const Product = initProduct(sequelize, Sequelize.DataTypes);
const Cart = initCart(sequelize, Sequelize.DataTypes);
const Order = initOrder(sequelize, Sequelize.DataTypes);
const OrderItem = initOrderItem(sequelize, Sequelize.DataTypes);
const Address = initAddress(sequelize); // 初始化地址模型

// 设置模型关联
Category.hasMany(Product, {
    foreignKey: 'categoryId',
    as: 'products',
    onDelete: 'CASCADE'
});

Product.belongsTo(Category, {
    foreignKey: 'categoryId',
    as: 'category'
});

// 设置Category自关联
Category.hasMany(Category, {
    foreignKey: 'parentId',
    as: 'children',
    onDelete: 'SET NULL'
});

Category.belongsTo(Category, {
    foreignKey: 'parentId',
    as: 'parent'
});

User.hasMany(Cart, {
    foreignKey: 'userId',
    as: 'cartItems',
    onDelete: 'CASCADE'
});

// 添加产品与购物车的关联
Product.hasMany(Cart, {
    foreignKey: 'productId',
    as: 'cartItems',
    onDelete: 'CASCADE'
});

Cart.belongsTo(User, {
    foreignKey: 'userId',
    as: 'user'
});

Cart.belongsTo(Product, {
    foreignKey: 'productId',
    as: 'product'
});

User.hasMany(Order, {
    foreignKey: 'userId',
    as: 'orders',
    onDelete: 'CASCADE'
});

Order.belongsTo(User, {
    foreignKey: 'userId',
    as: 'user'
});

Order.hasMany(OrderItem, {
    foreignKey: 'orderId',
    as: 'items',
    onDelete: 'CASCADE'
});

OrderItem.belongsTo(Order, {
    foreignKey: 'orderId',
    as: 'order'
});

OrderItem.belongsTo(Product, {
    foreignKey: 'productId',
    as: 'product'
});

// 添加用户与地址的关联
User.hasMany(Address, {
    foreignKey: 'userId',
    as: 'addresses',
    onDelete: 'CASCADE'
});

Address.belongsTo(User, {
    foreignKey: 'userId',
    as: 'user'
});

// 导出所有模型和 Sequelize 实例
exports.User = User;
exports.Category = Category;
exports.Product = Product;
exports.Cart = Cart;
exports.Order = Order;
exports.OrderItem = OrderItem;
exports.Address = Address; // 导出地址模型
exports.sequelize = sequelize;
exports.Sequelize = Sequelize;